package com.bitdf.txing.seckill.listener;

import com.bitdf.txing.seckill.service.SeckillService;
import com.bitdf.txing.seckill.to.SeckillTo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author Lizhiwei
 * @date 2023/8/26 17:06:15
 * 注释：
 */
@Service
@RabbitListener(queues = {"wait.exec.seckill.queue"})
@Slf4j
public class SeckillMqListener {

    @Autowired
    SeckillService seckillService;

    /**
     * 该监听器负责处理队列里的秒杀请求
     * @param seckillTo
     * @param channel
     * @param message
     * @throws IOException
     */
    @RabbitHandler
    public void listener(SeckillTo seckillTo, Channel channel, Message message) throws IOException {
        log.info("收到秒杀请求： {}, 开始执行秒杀", seckillTo.getKillId());
        try {
            // 开始执行请求
            seckillService.kill(seckillTo.getKillId(), seckillTo.getKey(), seckillTo.getNum());
            log.info("完成执行秒杀，确认消息");
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (InterruptedException | IOException e) {
            log.info("执行秒杀出错，重放消息");
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }



//    @RabbitHandler
//    public void listener(SeckillOrderTo orderTo, Channel channel, Message message) throws IOException {
//        log.info("收到秒杀结果（orderSn: {} skuId: {}）, 开始生成为其订单", orderTo.getOrderSn(), orderTo.getSkuId());
//        try {
//            boolean b = orderService.createSeckillOrder(orderTo);
//            if (b) {
//                log.info("成功生成订单");
//                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
//            } else {
//                throw new RuntimeException();
//            }
//        } catch (Exception e) {
//            log.info("生成订单失败：{}", orderTo.getOrderSn());
//            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
//        }
//    }

}
